import { onBeforeUnmount, ref } from "vue";
import type { Ref } from "vue";

type useCountdownType = { countdown: Ref<number>, start: Ref<boolean>, subCountdown: () => void }

const useCountdown = (time: number = 60): useCountdownType => {
    const countdown: Ref<number> = ref<number>(time);
    let start: Ref<boolean> = ref<boolean>(false);
    let timeId: ReturnType<typeof setTimeout>;
    const subCountdown = (): void => {
        start.value = true;
        clearInterval(timeId);
        timeId = setInterval((): void => {
            countdown.value--;
            if (countdown.value <= 0) {
                clearInterval(timeId);
                start.value = false;
                countdown.value = time;
            }
        }, 1000);
    };
    onBeforeUnmount(() => {
        clearInterval(timeId);
    });
    return {
        countdown,
        start,
        subCountdown,
    };
};


export default useCountdown;
